package cs131.pa1.filter.sequential;

import cs131.pa1.filter.Message;

import java.io.*;
import java.util.*;

import static cs131.pa1.filter.Message.CANNOT_HAVE_INPUT;
import static cs131.pa1.filter.Message.FILE_NOT_FOUND;
import static cs131.pa1.filter.Message.REQUIRES_INPUT;

public class CatCommand extends SequentialFilter {
    public final static String COMMAND = "cat";

    private List<String> params;

    public CatCommand(List<String> commands) {
        params = new ArrayList<String>();

        if(commands.size() < 2){
            System.out.print(Message.REQUIRES_PARAMETER.with_parameter(commands.get(0)));
            return;
        }
        for (int i = 1; i < commands.size(); i++) {
            this.params.add(commands.get(i));
        }
    }

    public void process() {

        if(prev != null){
            printWarning(CANNOT_HAVE_INPUT);
            return;
        }

        if (output == null) {
            this.output = new LinkedList<String>();
        }

        for (String param:params) {
            File file = new File(param);
            Scanner readFile = null;
            try {
                readFile = new Scanner(file);

                while (readFile.hasNextLine()) {
                    output.add(readFile.nextLine());
                }
            } catch (FileNotFoundException e) {
                printWarning(FILE_NOT_FOUND);
                return;
            } finally {
                if (readFile != null) {
                    readFile.close();
                }
            }
        }

        if (next == null) {
            for (String outInfo : output) {
                System.out.println(outInfo);
            }
        }

    }

    private void printWarning(Message message){
        StringBuilder sb = new StringBuilder(COMMAND);
        for(String str : params){
            sb.append(" " + str);
        }
        System.out.print(message.with_parameter(sb.toString()));
        setInterruption(true);
    }

    @Override
    protected String processLine(String line) {
        // TODO Auto-generated method stub
        return null;
    }

}
